﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.BasicList
{
    public partial class panel_RobotEndStructure : UserControl
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private SqlConnection masterConnection;

        public panel_RobotEndStructure()
        {
            InitializeComponent();

            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.masterConnection = new SqlConnection(mySetting.DB2ConnectionString);

            LoadData();

            this.RobotEndStructure.DoubleClick += Kosei_DoubleClick;
            this.RobotEndStructure.PopupMenuShowing += Kosei_PopupMenuShowing;
            this.robotEndStructureContext.ItemClicked += koseiContext_ItemClicked;
        }

        private void callEditForm()
        {
            DataRow row = RobotEndStructure.GetFocusedDataRow();
            frm_Edit_Kosei editForm = new frm_Edit_Kosei();
            editForm.kosei_id = row[0].ToString();
            if (editForm.LoadData())
            {
                //editForm.Show();
                editForm.ShowDialog();
                LoadData();
            }
            else
            {
                MessageBox.Show("Cannot load data for selected record");
            }
        }

        void Kosei_DoubleClick(object sender, EventArgs e)
        {
            callEditForm(); 
        }

        void koseiContext_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.robotEndStructureContext.Hide();            
            switch (e.ClickedItem.Name)
            {
                case "editSelection":
                    callEditForm();
                    break;
                case "refreshSelection":
                    LoadData();
                    break;
            }
        }

        void Kosei_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            this.robotEndStructureContext.Show(MousePosition);
        }

        ///////////////////////////////////
        /// Load Data From Local Database
        ///////////////////////////////////
        private void LoadData()
        {
            DataSet sourceDataSet = new DataSet();
            INISettings mySettings = new INISettings();
            SQLManagement mySQLManagement = new SQLManagement();
            mySQLManagement.SQLConnectionString = mySettings.SQLConnectionString;
            string sql = "SELECT ID, CompID, PartNo, Quantity, Size, Note FROM [222_Kosei]";
            sourceDataSet = mySQLManagement.SQL_Query(sql);
            if (sourceDataSet != null)
            {
                gridRobotEndStructure.DataSource = sourceDataSet.Tables[0];
                getUpdateInfo();
            }
            else
            {
                DataTable newTable = new DataTable();
                newTable.Columns.Add("ID", typeof(int));
                newTable.Columns.Add("CompID", typeof(string));
                newTable.Columns.Add("PartNo", typeof(string));
                newTable.Columns.Add("Quantity", typeof(string));
                newTable.Columns.Add("Size", typeof(string));
                newTable.Columns.Add("Note", typeof(string));
                gridRobotEndStructure.DataSource = newTable;
            }
            RobotEndStructure.Columns[0].Caption = "ID";
            RobotEndStructure.Columns[1].Caption = "Comp ID";
            RobotEndStructure.Columns[2].Caption = "Part No";
            RobotEndStructure.Columns[3].Caption = "Quantity";
            RobotEndStructure.Columns[4].Caption = "Size";
            RobotEndStructure.Columns[5].Caption = "Note";
            RobotEndStructure.Columns[0].Visible = false;
            RobotEndStructure.BestFitColumns();
        }

        /////////////////////////////////////
        /// Get Update Information
        /////////////////////////////////////
        private void getUpdateInfo()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT LastUpdate FROM [222_UpdateHistory] WHERE ID=1";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    this.updateDate.Text = dataReader["LastUpdate"].ToString();
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get update information");
            }
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }


        private void buttonEdit_Click(object sender, EventArgs e)
        {
            callEditForm(); 
        }

        ////////////////////////////////////
        /// Update database From AS400
        ////////////////////////////////////

        private void buttonImport_Click(object sender, EventArgs e)
        {
            DataSet as400 = new DataSet();
            DataSet kosei = new DataSet();
            string sql = null;
            SqlCommand cmd;
            SqlDataAdapter adapter;
            DataTable kosei_db2;
            DataTable kosei_local;                
            try
            {
                //Get Data From AS400
                
                masterConnection.Open();
                sql = "SELECT * FROM OPENQUERY(AS400_MPFLIB, 'SELECT MPST00.STOHBN,"
                    + " MPST00.STBHBN, MPST00.STKOSU, MPIT00.ITHNTP"
                    + " FROM MPST00 LEFT JOIN"
                    + " MPIT00 ON MPST00.STBHBN=MPIT00.ITHNBN"
                    + " WHERE MPIT00.ITHNTP = ''P'')";
                cmd = new SqlCommand(sql, masterConnection);
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(as400);
                kosei_db2 = as400.Tables[0];
                adapter.Dispose();
                cmd.Dispose();
                masterConnection.Close(); 
                /*
                myConnection.Open();
                sql = "SELECT RobotID, RobotName, Qty FROM [TestKosei]";
                cmd = new SqlCommand(sql, myConnection);
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(as400);
                kosei_db2 = as400.Tables[0];
                adapter.Dispose();
                cmd.Dispose();
                myConnection.Close();
                */


                //Get Data From Local Database
                myConnection.Open();
                sql = "SELECT * FROM [222_Kosei]";
                cmd = new SqlCommand(sql, myConnection);
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(kosei, "222_Kosei");
                kosei_local = kosei.Tables["222_Kosei"];
                
                foreach (DataRow as400_row in kosei_db2.Rows)
                {
                    DataRow[] current_row = kosei_local.Select("CompID='" + as400_row["STOHBN"].ToString() + "'"
                        + " AND PartNo='" + as400_row["STBHBN"].ToString() + "'");
                    if (current_row.Length > 0)
                    {
                        foreach (DataRow local_row in current_row)
                        {
                            local_row.BeginEdit();
                            local_row["Quantity"] = as400_row["STKOSU"];
                            local_row.EndEdit();
                        }
                    }
                    else
                    {
                        DataRow new_row = kosei_local.NewRow();
                        new_row["CompID"] = as400_row["STOHBN"].ToString();
                        new_row["PartNo"] = as400_row["STBHBN"].ToString();
                        new_row["Quantity"] = Int32.Parse(as400_row["STKOSU"].ToString());
                        kosei_local.Rows.Add(new_row);
                    }
                } 
                /*
                foreach (DataRow as400_row in kosei_db2.Rows)
                {
                    DataRow[] current_row = kosei_local.Select("CompID='" + as400_row["RobotID"].ToString()
                        + "' AND PartNo='" + as400_row["RobotName"].ToString() + "'");
                    if (current_row.Length > 0)
                    {
                        foreach (DataRow local_row in current_row)
                        {
                            local_row.BeginEdit();
                            local_row["Quantity"] = as400_row["Qty"];
                            local_row.EndEdit();
                        }
                    }
                    else
                    {
                        DataRow new_row = kosei_local.NewRow();
                        new_row["CompID"] = as400_row["RobotID"].ToString();
                        new_row["PartNo"] = as400_row["RobotName"].ToString();
                        new_row["Quantity"] = Int32.Parse(as400_row["Qty"].ToString());
                        kosei_local.Rows.Add(new_row);
                    }
                } */

                SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(adapter);
                //Update to Local Database
                adapter.Update(kosei, "222_Kosei");
                
                adapter.Dispose();
                cmd.Dispose();
                myConnection.Close();
                
                //Update History
                myConnection.Open();
                sql = "UPDATE [222_UpdateHistory] SET LastUpdate=GETDATE() WHERE ID=1";
                SqlCommand cmd_sql = new SqlCommand(sql, myConnection);                
                cmd_sql.ExecuteNonQuery();
                cmd_sql.Dispose();
                myConnection.Close();

                LoadData();

                MessageBox.Show("Database has been updated successfull.");
                                
            }
            catch (Exception ex)
            {
                if (masterConnection.State == ConnectionState.Open)
                {
                    masterConnection.Close();
                }

                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
                //MessageBox.Show("Cannot connect to AS400");
            }
        }
    }
}
